package com.jacksen.demo.view.socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * TCP 服务端
 */
public class TCPServerService extends Service {

    private boolean isServiceDestroyed = false;

    private String[] messages = new String[]{
            "nihao",
            "啊哈哈哈",
            "今天天气不错"
    };

    public TCPServerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new TcpServer()).start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class TcpServer implements Runnable {
        @Override
        public void run() {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(8688);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!isServiceDestroyed) {
                try {
                    final Socket client = serverSocket.accept();
                    Log.d("TcpServer", "accept a client");
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                responseClient(client);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void responseClient(Socket client) throws IOException {
        // 接收消息
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));

        // 发送消息
        PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
        printWriter.println("欢迎来到聊天室");

        while (!isServiceDestroyed) {
            String str = bufferedReader.readLine();
            Log.d("TCPServerService", "msg from client" + str);
            if (str == null) {
                break; // 断开连接
            }

            int i = new Random().nextInt(messages.length);
            String replyMsg = messages[i];
            printWriter.println(replyMsg);
            Log.d("TCPServerService", "server reply: " + replyMsg);
        }

        Log.d("TCPServerService", "client quit");
        printWriter.close();
        bufferedReader.close();
        client.close();

    }

    @Override
    public void onDestroy() {
        isServiceDestroyed = true;
        super.onDestroy();
    }
}
